// 主要JavaScript文件 - 个人工具网站集

// 全局变量
const App = {
  currentUser: null,
  currentCategory: 'all',
  tools: [],
  categories: [
    { id: 'all', name: '全部工具', icon: 'fas fa-th' },
    { id: 'development', name: '开发助手', icon: 'fas fa-code' },
    { id: 'image', name: '图像工具', icon: 'fas fa-image' },
    { id: 'document', name: '文档处理', icon: 'fas fa-file-alt' },
    { id: 'game', name: '小游戏', icon: 'fas fa-gamepad' },
    { id: 'utility', name: '实用工具', icon: 'fas fa-tools' }
  ],
  init: function() {
    this.bindEvents();
    this.loadTools();
    this.loadUserInfo();
    this.initializeComponents();
  }
};

// 事件绑定
App.bindEvents = function() {
  // 分类切换
  document.addEventListener('click', function(e) {
    if (e.target.matches('.category-link')) {
      e.preventDefault();
      const category = e.target.dataset.category;
      App.switchCategory(category);
    }
  });

  // 工具卡片点击
  document.addEventListener('click', function(e) {
    if (e.target.closest('.tool-card')) {
      const toolCard = e.target.closest('.tool-card');
      const toolId = toolCard.dataset.toolId;
      if (toolId) {
        App.openTool(toolId);
      }
    }
  });

  // 搜索功能
  const searchInput = document.getElementById('searchInput');
  if (searchInput) {
    searchInput.addEventListener('input', function(e) {
      App.searchTools(e.target.value);
    });
  }

  // 模态框关闭
  document.addEventListener('click', function(e) {
    if (e.target.matches('.modal-close') || e.target.matches('.modal')) {
      App.closeModal();
    }
  });

  // ESC键关闭模态框
  document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
      App.closeModal();
    }
  });

  // 文件上传
  const uploadArea = document.getElementById('uploadArea');
  if (uploadArea) {
    uploadArea.addEventListener('dragover', App.handleDragOver);
    uploadArea.addEventListener('drop', App.handleDrop);
    uploadArea.addEventListener('click', function() {
      document.getElementById('fileInput').click();
    });
  }

  const fileInput = document.getElementById('fileInput');
  if (fileInput) {
    fileInput.addEventListener('change', App.handleFileSelect);
  }

  // 表单提交
  const forms = document.querySelectorAll('form');
  forms.forEach(form => {
    form.addEventListener('submit', App.handleFormSubmit);
  });
};

// 分类切换
App.switchCategory = function(category) {
  this.currentCategory = category;
  
  // 更新侧边栏激活状态
  document.querySelectorAll('.category-link').forEach(link => {
    link.classList.remove('active');
  });
  document.querySelector(`[data-category="${category}"]`).classList.add('active');
  
  // 过滤工具
  this.filterTools();
};

// 工具过滤
App.filterTools = function() {
  const toolCards = document.querySelectorAll('.tool-card');
  
  toolCards.forEach(card => {
    const toolCategory = card.dataset.category;
    const shouldShow = this.currentCategory === 'all' || toolCategory === this.currentCategory;
    
    if (shouldShow) {
      card.style.display = 'flex';
      card.classList.add('fade-in');
    } else {
      card.style.display = 'none';
      card.classList.remove('fade-in');
    }
  });
  
  // 更新工具数量显示
  const visibleTools = document.querySelectorAll('.tool-card[style*="flex"]').length;
  const categoryName = this.categories.find(cat => cat.id === this.currentCategory)?.name || '全部工具';
  
  const titleElement = document.querySelector('.main-title');
  if (titleElement) {
    titleElement.textContent = `${categoryName} (${visibleTools})`;
  }
};

// 搜索工具
App.searchTools = function(query) {
  const toolCards = document.querySelectorAll('.tool-card');
  const searchQuery = query.toLowerCase().trim();
  
  toolCards.forEach(card => {
    const title = card.querySelector('.tool-card-title').textContent.toLowerCase();
    const description = card.querySelector('.tool-card-description').textContent.toLowerCase();
    const tags = card.dataset.tags ? card.dataset.tags.toLowerCase() : '';
    
    const matches = title.includes(searchQuery) || 
                   description.includes(searchQuery) || 
                   tags.includes(searchQuery);
    
    if (matches || searchQuery === '') {
      card.style.display = 'flex';
    } else {
      card.style.display = 'none';
    }
  });
  
  // 如果有搜索查询，显示搜索结果数量
  if (searchQuery) {
    const visibleTools = document.querySelectorAll('.tool-card[style*="flex"]').length;
    const titleElement = document.querySelector('.main-title');
    if (titleElement) {
      titleElement.textContent = `搜索结果 (${visibleTools})`;
    }
  } else {
    this.filterTools();
  }
};

// 打开工具
App.openTool = function(toolId) {
  // 增加访问量
  this.incrementToolViews(toolId);
  
  // 跳转到工具页面
  window.location.href = `/tool/${toolId}`;
};

// 增加工具访问量
App.incrementToolViews = function(toolId) {
  fetch(`/api/tools/${toolId}/view`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    }
  }).catch(error => {
    console.error('Failed to increment views:', error);
  });
};

// 加载工具数据
App.loadTools = function() {
  fetch('/api/tools')
    .then(response => response.json())
    .then(data => {
      this.tools = data.tools || [];
      this.renderTools();
    })
    .catch(error => {
      console.error('Failed to load tools:', error);
      this.showMessage('加载工具失败', 'error');
    });
};

// 渲染工具卡片
App.renderTools = function() {
  const toolsContainer = document.getElementById('toolsContainer');
  if (!toolsContainer) return;
  
  toolsContainer.innerHTML = '';
  
  this.tools.forEach(tool => {
    const toolCard = this.createToolCard(tool);
    toolsContainer.appendChild(toolCard);
  });
  
  // 应用当前过滤器
  this.filterTools();
};

// 创建工具卡片
App.createToolCard = function(tool) {
  const card = document.createElement('div');
  card.className = 'tool-card';
  card.dataset.toolId = tool.id;
  card.dataset.category = tool.category;
  card.dataset.tags = tool.tags ? tool.tags.join(',') : '';
  
  card.innerHTML = `
    <div class="tool-card-header">
      <div class="tool-card-icon">
        <i class="${tool.icon || 'fas fa-tools'}"></i>
      </div>
      <h3 class="tool-card-title">${tool.name}</h3>
    </div>
    <p class="tool-card-description">${tool.description}</p>
    <div class="tool-card-footer">
      <div class="tool-card-stats">
        <span><i class="fas fa-eye"></i> ${tool.views || 0}</span>
        <span><i class="fas fa-heart"></i> ${tool.likes || 0}</span>
      </div>
      <span class="tool-card-category">${this.getCategoryName(tool.category)}</span>
    </div>
  `;
  
  return card;
};

// 获取分类名称
App.getCategoryName = function(categoryId) {
  const category = this.categories.find(cat => cat.id === categoryId);
  return category ? category.name : '其他';
};

// 加载用户信息
App.loadUserInfo = function() {
  fetch('/api/user/info')
    .then(response => response.json())
    .then(data => {
      if (data.user) {
        this.currentUser = data.user;
        this.updateUserUI();
      }
    })
    .catch(error => {
      console.error('Failed to load user info:', error);
    });
};

// 更新用户界面
App.updateUserUI = function() {
  const userInfo = document.getElementById('userInfo');
  if (userInfo && this.currentUser) {
    userInfo.innerHTML = `
      <div class="user-avatar">
        <i class="fas fa-user"></i>
      </div>
      <span class="user-name">${this.currentUser.username}</span>
      <div class="user-menu">
        <a href="/profile" class="btn btn-sm btn-secondary">
          <i class="fas fa-cog"></i> 个人中心
        </a>
        <button onclick="App.logout()" class="btn btn-sm btn-secondary">
          <i class="fas fa-sign-out-alt"></i> 退出
        </button>
      </div>
    `;
  }
};

// 用户登出
App.logout = function() {
  fetch('/api/auth/logout', {
    method: 'POST'
  })
  .then(() => {
    window.location.href = '/login';
  })
  .catch(error => {
    console.error('Logout failed:', error);
  });
};

// 文件拖拽处理
App.handleDragOver = function(e) {
  e.preventDefault();
  e.currentTarget.classList.add('dragover');
};

App.handleDrop = function(e) {
  e.preventDefault();
  e.currentTarget.classList.remove('dragover');
  
  const files = e.dataTransfer.files;
  if (files.length > 0) {
    App.handleFiles(files);
  }
};

App.handleFileSelect = function(e) {
  const files = e.target.files;
  if (files.length > 0) {
    App.handleFiles(files);
  }
};

// 文件处理
App.handleFiles = function(files) {
  const file = files[0];
  
  // 验证文件类型
  if (!file.name.toLowerCase().endsWith('.html')) {
    this.showMessage('请选择HTML文件', 'error');
    return;
  }
  
  // 验证文件大小 (5MB)
  if (file.size > 5 * 1024 * 1024) {
    this.showMessage('文件大小不能超过5MB', 'error');
    return;
  }
  
  // 显示文件信息
  const fileInfo = document.getElementById('fileInfo');
  if (fileInfo) {
    fileInfo.innerHTML = `
      <div class="file-preview">
        <i class="fas fa-file-code"></i>
        <div class="file-details">
          <div class="file-name">${file.name}</div>
          <div class="file-size">${this.formatFileSize(file.size)}</div>
        </div>
      </div>
    `;
  }
  
  // 启用上传按钮
  const uploadBtn = document.getElementById('uploadBtn');
  if (uploadBtn) {
    uploadBtn.disabled = false;
    uploadBtn.dataset.file = file.name;
  }
};

// 格式化文件大小
App.formatFileSize = function(bytes) {
  if (bytes === 0) return '0 Bytes';
  
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 表单提交处理
App.handleFormSubmit = function(e) {
  e.preventDefault();
  
  const form = e.target;
  const formData = new FormData(form);
  const submitBtn = form.querySelector('button[type="submit"]');
  
  // 显示加载状态
  if (submitBtn) {
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<span class="loading"></span> 提交中...';
  }
  
  // 获取表单action和method
  const action = form.action || window.location.pathname;
  const method = form.method || 'POST';
  
  fetch(action, {
    method: method,
    body: formData
  })
  .then(response => response.json())
  .then(data => {
    if (data.success) {
      App.showMessage(data.message || '操作成功', 'success');
      
      // 根据表单类型执行不同操作
      if (form.id === 'uploadForm') {
        App.handleUploadSuccess(data);
      } else if (form.id === 'loginForm') {
        window.location.href = data.redirect || '/';
      } else if (form.id === 'registerForm') {
        window.location.href = '/verify-email';
      }
    } else {
      App.showMessage(data.message || '操作失败', 'error');
    }
  })
  .catch(error => {
    console.error('Form submission error:', error);
    App.showMessage('网络错误，请重试', 'error');
  })
  .finally(() => {
    // 恢复按钮状态
    if (submitBtn) {
      submitBtn.disabled = false;
      submitBtn.innerHTML = submitBtn.dataset.originalText || '提交';
    }
  });
};

// 上传成功处理
App.handleUploadSuccess = function(data) {
  // 重置表单
  const form = document.getElementById('uploadForm');
  if (form) {
    form.reset();
  }
  
  // 清空文件信息
  const fileInfo = document.getElementById('fileInfo');
  if (fileInfo) {
    fileInfo.innerHTML = '';
  }
  
  // 禁用上传按钮
  const uploadBtn = document.getElementById('uploadBtn');
  if (uploadBtn) {
    uploadBtn.disabled = true;
  }
  
  // 如果有工具URL，显示访问链接
  if (data.tool_url) {
    const successMessage = `
      <div class="upload-success">
        <h4>上传成功！</h4>
        <p>您的工具已成功上传，可以通过以下链接访问：</p>
        <a href="${data.tool_url}" target="_blank" class="btn btn-primary">
          <i class="fas fa-external-link-alt"></i> 访问工具
        </a>
      </div>
    `;
    
    const resultContainer = document.getElementById('uploadResult');
    if (resultContainer) {
      resultContainer.innerHTML = successMessage;
    }
  }
  
  // 刷新工具列表
  this.loadTools();
};

// 显示消息
App.showMessage = function(message, type = 'info') {
  // 移除现有消息
  const existingMessage = document.querySelector('.message-toast');
  if (existingMessage) {
    existingMessage.remove();
  }
  
  // 创建新消息
  const messageEl = document.createElement('div');
  messageEl.className = `message-toast alert alert-${type}`;
  messageEl.innerHTML = `
    <i class="fas fa-${this.getMessageIcon(type)}"></i>
    <span>${message}</span>
    <button class="message-close" onclick="this.parentElement.remove()">
      <i class="fas fa-times"></i>
    </button>
  `;
  
  // 添加到页面
  document.body.appendChild(messageEl);
  
  // 自动移除
  setTimeout(() => {
    if (messageEl.parentElement) {
      messageEl.remove();
    }
  }, 5000);
};

// 获取消息图标
App.getMessageIcon = function(type) {
  const icons = {
    success: 'check-circle',
    error: 'exclamation-circle',
    warning: 'exclamation-triangle',
    info: 'info-circle'
  };
  return icons[type] || 'info-circle';
};

// 模态框操作
App.showModal = function(modalId) {
  const modal = document.getElementById(modalId);
  if (modal) {
    modal.style.display = 'flex';
    document.body.style.overflow = 'hidden';
  }
};

App.closeModal = function() {
  const modals = document.querySelectorAll('.modal');
  modals.forEach(modal => {
    modal.style.display = 'none';
  });
  document.body.style.overflow = 'auto';
};

// 工具分享
App.shareTool = function(toolId) {
  const tool = this.tools.find(t => t.id === toolId);
  if (!tool) return;
  
  const shareUrl = `${window.location.origin}/tool/${toolId}`;
  
  if (navigator.share) {
    navigator.share({
      title: tool.name,
      text: tool.description,
      url: shareUrl
    }).catch(error => {
      console.error('Share failed:', error);
      this.copyToClipboard(shareUrl);
    });
  } else {
    this.copyToClipboard(shareUrl);
  }
};

// 复制到剪贴板
App.copyToClipboard = function(text) {
  if (navigator.clipboard) {
    navigator.clipboard.writeText(text).then(() => {
      this.showMessage('链接已复制到剪贴板', 'success');
    }).catch(error => {
      console.error('Copy failed:', error);
      this.fallbackCopyTextToClipboard(text);
    });
  } else {
    this.fallbackCopyTextToClipboard(text);
  }
};

// 备用复制方法
App.fallbackCopyTextToClipboard = function(text) {
  const textArea = document.createElement('textarea');
  textArea.value = text;
  textArea.style.position = 'fixed';
  textArea.style.left = '-999999px';
  textArea.style.top = '-999999px';
  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();
  
  try {
    document.execCommand('copy');
    this.showMessage('链接已复制到剪贴板', 'success');
  } catch (err) {
    console.error('Fallback copy failed:', err);
    this.showMessage('复制失败，请手动复制链接', 'error');
  }
  
  document.body.removeChild(textArea);
};

// 工具点赞
App.likeTool = function(toolId) {
  fetch(`/api/tools/${toolId}/like`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    }
  })
  .then(response => response.json())
  .then(data => {
    if (data.success) {
      // 更新点赞数
      const likeBtn = document.querySelector(`[data-tool-id="${toolId}"] .like-btn`);
      if (likeBtn) {
        const likeCount = likeBtn.querySelector('.like-count');
        if (likeCount) {
          likeCount.textContent = data.likes;
        }
        likeBtn.classList.toggle('liked', data.liked);
      }
    }
  })
  .catch(error => {
    console.error('Like failed:', error);
    this.showMessage('操作失败，请重试', 'error');
  });
};

// 初始化组件
App.initializeComponents = function() {
  // 初始化工具提示
  this.initTooltips();
  
  // 初始化懒加载
  this.initLazyLoading();
  
  // 初始化键盘快捷键
  this.initKeyboardShortcuts();
  
  // 初始化主题切换
  this.initThemeToggle();
};

// 初始化工具提示
App.initTooltips = function() {
  const tooltipElements = document.querySelectorAll('[data-tooltip]');
  tooltipElements.forEach(element => {
    element.addEventListener('mouseenter', function() {
      this.classList.add('tooltip-show');
    });
    element.addEventListener('mouseleave', function() {
      this.classList.remove('tooltip-show');
    });
  });
};

// 初始化懒加载
App.initLazyLoading = function() {
  if ('IntersectionObserver' in window) {
    const imageObserver = new IntersectionObserver((entries, observer) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          const img = entry.target;
          img.src = img.dataset.src;
          img.classList.remove('lazy');
          observer.unobserve(img);
        }
      });
    });
    
    document.querySelectorAll('img[data-src]').forEach(img => {
      imageObserver.observe(img);
    });
  }
};

// 初始化键盘快捷键
App.initKeyboardShortcuts = function() {
  document.addEventListener('keydown', function(e) {
    // Ctrl/Cmd + K 打开搜索
    if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
      e.preventDefault();
      const searchInput = document.getElementById('searchInput');
      if (searchInput) {
        searchInput.focus();
      }
    }
    
    // Ctrl/Cmd + U 打开上传
    if ((e.ctrlKey || e.metaKey) && e.key === 'u') {
      e.preventDefault();
      const uploadBtn = document.querySelector('[data-action="upload"]');
      if (uploadBtn) {
        uploadBtn.click();
      }
    }
  });
};

// 初始化主题切换
App.initThemeToggle = function() {
  const themeToggle = document.getElementById('themeToggle');
  if (themeToggle) {
    themeToggle.addEventListener('click', function() {
      const currentTheme = document.documentElement.getAttribute('data-theme');
      const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
      
      document.documentElement.setAttribute('data-theme', newTheme);
      localStorage.setItem('theme', newTheme);
      
      // 更新图标
      const icon = this.querySelector('i');
      if (icon) {
        icon.className = newTheme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
      }
    });
    
    // 加载保存的主题
    const savedTheme = localStorage.getItem('theme') || 'light';
    document.documentElement.setAttribute('data-theme', savedTheme);
    
    const icon = themeToggle.querySelector('i');
    if (icon) {
      icon.className = savedTheme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
    }
  }
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
  App.init();
});

// 导出到全局
window.App = App;

// 工具函数
window.utils = {
  // 防抖函数
  debounce: function(func, wait) {
    let timeout;
    return function executedFunction(...args) {
      const later = () => {
        clearTimeout(timeout);
        func(...args);
      };
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
    };
  },
  
  // 节流函数
  throttle: function(func, limit) {
    let inThrottle;
    return function() {
      const args = arguments;
      const context = this;
      if (!inThrottle) {
        func.apply(context, args);
        inThrottle = true;
        setTimeout(() => inThrottle = false, limit);
      }
    };
  },
  
  // 格式化日期
  formatDate: function(date) {
    const now = new Date();
    const diff = now - new Date(date);
    const seconds = Math.floor(diff / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);
    
    if (days > 0) {
      return `${days}天前`;
    } else if (hours > 0) {
      return `${hours}小时前`;
    } else if (minutes > 0) {
      return `${minutes}分钟前`;
    } else {
      return '刚刚';
    }
  },
  
  // 验证邮箱
  validateEmail: function(email) {
    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return re.test(email);
  },
  
  // 验证密码强度
  validatePassword: function(password) {
    const minLength = password.length >= 8;
    const hasUpper = /[A-Z]/.test(password);
    const hasLower = /[a-z]/.test(password);
    const hasNumber = /\d/.test(password);
    const hasSpecial = /[!@#$%^&*(),.?":{}|<>]/.test(password);
    
    let strength = 0;
    if (minLength) strength++;
    if (hasUpper) strength++;
    if (hasLower) strength++;
    if (hasNumber) strength++;
    if (hasSpecial) strength++;
    
    return {
      score: strength,
      isValid: strength >= 3,
      feedback: {
        minLength,
        hasUpper,
        hasLower,
        hasNumber,
        hasSpecial
      }
    };
  }
};

// 消息提示样式
const messageStyles = `
.message-toast {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 1000;
  min-width: 300px;
  max-width: 500px;
  padding: 1rem 1.5rem;
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-lg);
  display: flex;
  align-items: center;
  gap: 0.75rem;
  animation: slideInRight 0.3s ease-out;
}

.message-close {
  background: none;
  border: none;
  color: inherit;
  cursor: pointer;
  padding: 0.25rem;
  margin-left: auto;
  border-radius: var(--radius-sm);
  transition: var(--transition);
}

.message-close:hover {
  background: rgba(0, 0, 0, 0.1);
}

@keyframes slideInRight {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}
`;

// 添加样式到页面
if (!document.getElementById('message-styles')) {
  const styleSheet = document.createElement('style');
  styleSheet.id = 'message-styles';
  styleSheet.textContent = messageStyles;
  document.head.appendChild(styleSheet);
}